package org.example.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.example.domain.User;
import org.example.mapper.DateMapper;

/**
 * @author 李新雨的项目86176
 * @version 1.0
 * @date 2024-12-14 18:50
 */
public class UserRealm extends AuthorizingRealm {

    //自定义Realm名称
    @Override
    public String getName() {
        return "userRealm";
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("自定义Realm认证");
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;
        //从token中获取用户名
        String employeeUserName = usernamePasswordToken.getUsername();
        System.out.println(employeeUserName);
        //从数据库中查询数据 ，根据用户名查询数据  对象
//        SqlSession session = MyBatisUtil.getSession();
//        EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
//        Employee employee=employeeMapper.selByUserNameGetEmployee(employeeUserName);
        User user = DateMapper.getUserByName(employeeUserName);
        System.out.println(user);
        if(user==null) {//用户不存在
          return null;
        }
        //自定义Realm名称
//        System.out.println(this.getName().toString());
        //
//        System.out.println("userRealm认证成功");
         return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
    /*    //提供数据
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;
        //从token中获取用户名
        String username = usernamePasswordToken.getUsername();

        //从数据库中查询数据 ，根据用户名查询数据  对象
        User user = DateMapper.getUserByName(username);
        if(user==null) {//用户名不存在
//            throw new UnknownAccountException("用户名不存在");
            System.out.println();
        }

        //将数据封装，
        /**
         *密码比对
         *
         * 首先是将输入用户名与密码保存到token中， subject.login(token);
         * realm中通过token对象获取用户名称，通过用户名称去查询数据库，将对象保存到SimpleAuthenticationInfo(user,user.getPassword(),getName());
         * 框架--------------------将token中密码【用户传递的密码】与
         *                         SimpleAuthenticationInfo(user,user.getPassword(),getName())【数据库的密码】比对
         *
         *        UsernamePasswordToken token=new UsernamePasswordToken("yl66","888");
         *
         *         User user = DateMapper.getUserByName(username);
         *
         *        user.getPassword()。equals(token.getPassword());
         *
         *
         * user对象可以保存到--subject中
         * 可以获取用户信息
         * System.out.println(subject.getPrincipal().toString());
         */
        // return new SimpleAuthenticationInfo(user,user.getPassword(),getName());

    }
}
